<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Go语言网关开发, 博客">
    <meta name="description" content="个人学习储备知识与经验的秘密基地">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=G-KDXT8Y4CLW"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', 'G-KDXT8Y4CLW');
</script>


    <title>Go语言网关开发 | 不二博客</title>
    <link rel="icon" type="image/png" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/favicon.png">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/matery.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/my.css">

    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="不二博客" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">不二博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">不二博客</div>
        <div class="logo-desc">
            
            个人学习储备知识与经验的秘密基地
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/weiyouwozuiku" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/weiyouwozuiku" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/程序设计/go.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Go语言网关开发</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go/">
                                <span class="chip bg-color">Go</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" class="post-category">
                                程序设计
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-12-18
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-10-31
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    24 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="网络基础">网络基础<a class="anchor" href="#网络基础">¶</a></h2>
<h3 id="协议模型">协议模型<a class="anchor" href="#协议模型">¶</a></h3>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/OSI%E4%B8%83%E5%B1%82%E7%BD%91%E7%BB%9C%E5%8D%8F%E8%AE%AE.png" alt="OSI七层网络协议.png"></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/%E7%BB%8F%E5%85%B8%E5%8D%8F%E8%AE%AE%E4%B8%8E%E6%95%B0%E6%8D%AE%E5%8C%85.png" alt="经典协议与数据包.png"></p>
<h3 id="TCP连接">TCP连接<a class="anchor" href="#TCP连接">¶</a></h3>
<p><strong>TCP的三次握手最主要目的是保证连接是双工的，可靠更多的是通过重传机制来保证。因为连接是全双工的，双方必须都收到对方的FIN包及确认才可关闭。</strong></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/%E4%B8%89%E6%AC%A1%E6%8F%A1%E6%89%8B%E8%BF%9E%E6%8E%A5.png" alt="三次握手连接.png"></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/%E5%9B%9B%E6%AC%A1%E5%9B%9E%E6%94%B6%E5%85%B3%E9%97%AD.png" alt="四次回收关闭.png"></p>
<p>MSL：Maximum Segment Lifetime,30秒到1分钟。</p>
<p><strong>TIME-WAIT等待2MSL是保证TCP协议的全双工连接能够可靠关闭。保证这次连接的重复数据段从网络中消失。</strong></p>
<p>大量出现close_wait的原因：</p>
<ol>
<li>一般出现在被动关闭方</li>
<li>并发请求太多导致</li>
<li>被动关闭方未及时释放端口资源导致</li>
</ol>
<h3 id="TCP流量控制">TCP流量控制<a class="anchor" href="#TCP流量控制">¶</a></h3>
<p>由于通讯双方，网速不同。通讯方任一方发送过快都会导致对方消息处理不过来，所以就需要把数据放在缓冲区中。如果缓冲区满了，发送方还在发送，那接收方只能把数据包丢弃。因此需要控制发送速率。</p>
<p>缓冲区大小称之为接收端口，用变量win表示。如果win=0，则发送方停止发送。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/TCP%E6%B5%81%E9%87%8F%E6%8E%A7%E5%88%B6.png" alt="TCP流量控制.png"></p>
<h3 id="TCP拥塞控制">TCP拥塞控制<a class="anchor" href="#TCP拥塞控制">¶</a></h3>
<p>拥塞控制是调节网络的负载。接收方网络资源繁忙，因未及时响应ACK导致发送方重传大量数据，这样将会导致网络更加拥堵。<strong>拥塞控制是动态调整win大小，不知是依赖缓冲区大小确定窗口大小</strong>。</p>
<h4 id="慢开始和拥塞避免">慢开始和拥塞避免<a class="anchor" href="#慢开始和拥塞避免">¶</a></h4>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/%E6%85%A2%E5%BC%80%E5%A7%8B%E4%B8%8E%E6%8B%A5%E5%A1%9E%E9%81%BF%E5%85%8D.png" alt="慢开始与拥塞避免.png"></p>
<h4 id="快速重传和快速恢复">快速重传和快速恢复<a class="anchor" href="#快速重传和快速恢复">¶</a></h4>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/%E5%BF%AB%E9%87%8D%E4%BC%A0%E5%92%8C%E5%BF%AB%E6%81%A2%E5%A4%8D.png" alt="快重传和快恢复.png"></p>
<h3 id="粘包和拆包">粘包和拆包<a class="anchor" href="#粘包和拆包">¶</a></h3>
<p>发生的情况：</p>
<ul>
<li>应用程序写入的数据大于套接字缓冲区大小，这将会发生拆包。</li>
<li>应用程序写入数据小于套接字缓冲区大小，网卡将应用多次写入的数据发送到网络上，这将会发生粘包。</li>
<li>进行MSS（最大报文长度）大小的TCP分段，当TCP报文长度-TCP头部长度&gt;MSS的时候将会发生拆包。</li>
<li>接收方法不及时读取套接字缓冲区数据，这将发生粘包。</li>
</ul>
<h3 id="数据传输协议">数据传输协议<a class="anchor" href="#数据传输协议">¶</a></h3>
<ul>
<li>使用带消息头的协议，头部写入包长度，然后再读取包内容</li>
<li>设置定长消息，每次读取定长内容，长度不够时空位补固定字段</li>
<li>设置消息边界，服务端从网络流中按消息边界分理出消息内容，一般使用<code>\n</code></li>
<li>专有的协议：json，protobuf</li>
</ul>
<h3 id="网络代理和网络转发区别">网络代理和网络转发区别<a class="anchor" href="#网络代理和网络转发区别">¶</a></h3>
<ul>
<li>网络代理
<ul>
<li>用户不直接连接服务器，网络代理去连接。获取数据后返回给用户。</li>
</ul>
</li>
<li>网络转发
<ul>
<li>路由器对报文的转发操作，中间可能对数据包修改。</li>
</ul>
</li>
</ul>
<h3 id="网络代理">网络代理<a class="anchor" href="#网络代理">¶</a></h3>
<h4 id="正向代理">正向代理<a class="anchor" href="#正向代理">¶</a></h4>
<p>是一种客户端的代理技术，帮助客户端访问无法访问的服务资源，可以隐藏用户真实IP。</p>
<h4 id="反向代理">反向代理<a class="anchor" href="#反向代理">¶</a></h4>
<p>是一种服务端的代理技术，帮助服务器做负载均衡、缓存、提供安全校验等，可以隐藏服务器真实IP。</p>
<h2 id="UDP创建过程">UDP创建过程<a class="anchor" href="#UDP创建过程">¶</a></h2>
<h3 id="Server">Server<a class="anchor" href="#Server">¶</a></h3>
<p>步骤：</p>
<ol>
<li>监听服务器</li>
<li>循环读取消息（不创建socket）</li>
<li>回复数据</li>
</ol>
<h3 id="Client">Client<a class="anchor" href="#Client">¶</a></h3>
<p>步骤：</p>
<ol>
<li>连接服务器</li>
<li>发送数据</li>
<li>接收数据</li>
</ol>
<h2 id="TCP创建过程">TCP创建过程<a class="anchor" href="#TCP创建过程">¶</a></h2>
<h3 id="Server-2">Server<a class="anchor" href="#Server-2">¶</a></h3>
<p>步骤：</p>
<ol>
<li>监听端口</li>
<li>接受请求，创建套接字连接</li>
<li>创建独立协程</li>
<li>数据解码</li>
</ol>
<h3 id="Client-2">Client<a class="anchor" href="#Client-2">¶</a></h3>
<p>步骤：</p>
<ol>
<li>连接服务器</li>
<li>将信息写入套接字，数据编码</li>
</ol>
<h2 id="HTTP创建过程">HTTP创建过程<a class="anchor" href="#HTTP创建过程">¶</a></h2>
<pre class="mermaid">graph LR;
HTTP--&gt;Server
Server--&gt;创建路由器
Server--&gt;设置路由规则
Server--&gt;创建服务器
Server--&gt;监听端口并提供服务
HTTP--&gt;Client
Client--&gt;创建连接池
Client--&gt;创建客户端
Client--&gt;请求数据
Client--&gt;读取内容</pre>
<h4 id="Server-3">Server<a class="anchor" href="#Server-3">¶</a></h4>
<p>主要结构体：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> ServeMux <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	mu    sync<span class="token punctuation">.</span>RWMutex
	m     <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span>muxEntry
	es    <span class="token punctuation">[</span><span class="token punctuation">]</span>muxEntry <span class="token comment">// slice of entries sorted from longest to shortest.</span>
	hosts <span class="token builtin">bool</span>       <span class="token comment">// whether any patterns contain hostnames</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> muxEntry <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	h       Handler
	pattern <span class="token builtin">string</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> Handler <span class="token keyword">interface</span> <span class="token punctuation">{</span>
	<span class="token function">ServeHTTP</span><span class="token punctuation">(</span>ResponseWriter<span class="token punctuation">,</span> <span class="token operator">*</span>Request<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>步骤：</p>
<ol>
<li>创建路由器 http.NewServeMux</li>
<li>设置路由规则 http.HandleFunc-&gt;http.Handle</li>
<li>创建服务器 http.Server</li>
<li>监听端口并提供服务 http.Server.ListenAndServe-&gt;http.server.Serve-&gt;http.Accept()-&gt;http.newConn-&gt;go c.serve-&gt;mux.ServeHTTP0&gt;mux.Handler®-&gt;mux.handler(r.host,r.URL.Path)-&gt;mux.match(path)-&gt;v,ok:=mux.m[path]</li>
</ol>
<h4 id="Client-3">Client<a class="anchor" href="#Client-3">¶</a></h4>
<p>主要结构体：
http.Client-&gt;Timeout &amp;&amp; Transport
type RoundTripper interface</p>
<p>步骤：</p>
<ol>
<li>创建连接池 http.Transport</li>
<li>创建客户端 http.Client</li>
<li>请求数据 func(c *Client) Get(url string)-&gt;c.DO(req)-&gt;c.do(req)-&gt;c.send(req,deadline)-&gt;send(req,c.transport(),deadline)-&gt;resq,err=rt.RoundTrip(req)&amp;&amp;func(t *Transport)roundTrip(req *Request)</li>
<li>读取数据</li>
</ol>
<h5 id="Transport">Transport<a class="anchor" href="#Transport">¶</a></h5>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Transport <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	idleMu       sync<span class="token punctuation">.</span>Mutex
	closeIdle    <span class="token builtin">bool</span>                                <span class="token comment">// user has requested to close all idle conns</span>
	idleConn     <span class="token keyword">map</span><span class="token punctuation">[</span>connectMethodKey<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>persistConn <span class="token comment">// most recently used at end</span>
	idleConnWait <span class="token keyword">map</span><span class="token punctuation">[</span>connectMethodKey<span class="token punctuation">]</span>wantConnQueue  <span class="token comment">// waiting getConns</span>
    <span class="token operator">...</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> connectMethodKey <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	proxy<span class="token punctuation">,</span> scheme<span class="token punctuation">,</span> addr <span class="token builtin">string</span>
	onlyH1              <span class="token builtin">bool</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="persistConn">persistConn<a class="anchor" href="#persistConn">¶</a></h5>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> persistConn <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	br        <span class="token operator">*</span>bufio<span class="token punctuation">.</span>Reader       <span class="token comment">// from conn</span>
	bw        <span class="token operator">*</span>bufio<span class="token punctuation">.</span>Writer       <span class="token comment">// to conn</span>
	reqch     <span class="token keyword">chan</span> requestAndChan <span class="token comment">// written by roundTrip; read by readLoop</span>
	writech   <span class="token keyword">chan</span> writeRequest   <span class="token comment">// written by roundTrip; read by writeLoop</span>
	<span class="token operator">...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="RoundTrip流程">RoundTrip流程<a class="anchor" href="#RoundTrip流程">¶</a></h5>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/Transport_RoundTrip%E6%B5%81%E7%A8%8B.png" alt="Transport_RoundTrip流程.png"></p>
<h4 id="超时时间">超时时间<a class="anchor" href="#超时时间">¶</a></h4>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E8%AF%AD%E8%A8%80%E7%BD%91%E5%85%B3%E5%BC%80%E5%8F%91/Client%E8%B6%85%E6%97%B6%E6%97%B6%E9%97%B4.png" alt="Client超时时间.png"></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">   <span class="token comment">// 创建连接池</span>
transport <span class="token operator">:=</span> <span class="token operator">&amp;</span>http<span class="token punctuation">.</span>Transport<span class="token punctuation">{</span>
	DialContext<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token operator">&amp;</span>net<span class="token punctuation">.</span>Dialer<span class="token punctuation">{</span>
		Timeout<span class="token punctuation">:</span>   <span class="token number">30</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span> <span class="token comment">//连接超时</span>
		KeepAlive<span class="token punctuation">:</span> <span class="token number">30</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span> <span class="token comment">//探活时间</span>
	<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span>DialContext<span class="token punctuation">,</span>
	MaxIdleConns<span class="token punctuation">:</span>          <span class="token number">100</span><span class="token punctuation">,</span>              <span class="token comment">//最大空闲连接</span>
	IdleConnTimeout<span class="token punctuation">:</span>       <span class="token number">90</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span> <span class="token comment">//空闲超时时间</span>
	TLSHandshakeTimeout<span class="token punctuation">:</span>   <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span> <span class="token comment">//tls握手超时时间</span>
	ExpectContinueTimeout<span class="token punctuation">:</span> <span class="token number">1</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>  <span class="token comment">//100-continue状态码超时时间</span>
<span class="token punctuation">}</span>
<span class="token comment">// 创建客户端</span>
client <span class="token operator">:=</span> <span class="token operator">&amp;</span>http<span class="token punctuation">.</span>Client<span class="token punctuation">{</span>
	Timeout<span class="token punctuation">:</span>   time<span class="token punctuation">.</span>Second <span class="token operator">*</span> <span class="token number">30</span><span class="token punctuation">,</span> <span class="token comment">//请求超时时间</span>
	Transport<span class="token punctuation">:</span> transport<span class="token punctuation">,</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="网络代理-2">网络代理<a class="anchor" href="#网络代理-2">¶</a></h2>
<p>网络代理 v.s 网络转发：</p>
<ul>
<li>网络代理：用户不直接连接服务器，网络代理去连接。获取数据后返回给用户。</li>
<li>网络转发：是路由器对报文的转发操作，中间可能堆数据包修改。</li>
</ul>
<h3 id="正向代理-2">正向代理<a class="anchor" href="#正向代理-2">¶</a></h3>
<p>正向代理：是一种<strong>客户端</strong>的代理技术。帮助客户端访问无法访问的服务资源，可以隐藏用户真实IP。</p>
<ol>
<li>代理接收客户端请求，复制原请求对象，并根据数据配置新请求各种参数</li>
<li>把新请求发送到真实服务端，并接收到服务器返回</li>
<li>代理服务器相应做一些处理，然后返回给客户端</li>
</ol>
<h4 id="http代理">http代理<a class="anchor" href="#http代理">¶</a></h4>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"io"</span>
	<span class="token string">"net"</span>
	<span class="token string">"net/http"</span>
	<span class="token string">"strings"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> Pxy <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>Pxy<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>rw http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> req <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Received request %s %s %s\n"</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span>Method<span class="token punctuation">,</span> req<span class="token punctuation">.</span>Host<span class="token punctuation">,</span> req<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span>
	transport <span class="token operator">:=</span> http<span class="token punctuation">.</span>DefaultTransport
	<span class="token comment">// step 1，浅拷贝对象，然后就再新增属性数据</span>
	outReq <span class="token operator">:=</span> <span class="token function">new</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span>
	<span class="token operator">*</span>outReq <span class="token operator">=</span> <span class="token operator">*</span>req
	<span class="token keyword">if</span> clientIP<span class="token punctuation">,</span> <span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">:=</span> net<span class="token punctuation">.</span><span class="token function">SplitHostPort</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">if</span> prior<span class="token punctuation">,</span> ok <span class="token operator">:=</span> outReq<span class="token punctuation">.</span>Header<span class="token punctuation">[</span><span class="token string">"X-Forwarded-For"</span><span class="token punctuation">]</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
			clientIP <span class="token operator">=</span> strings<span class="token punctuation">.</span><span class="token function">Join</span><span class="token punctuation">(</span>prior<span class="token punctuation">,</span> <span class="token string">", "</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">", "</span> <span class="token operator">+</span> clientIP
		<span class="token punctuation">}</span>
		outReq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"X-Forwarded-For"</span><span class="token punctuation">,</span> clientIP<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	
	<span class="token comment">// step 2, 请求下游</span>
	res<span class="token punctuation">,</span> err <span class="token operator">:=</span> transport<span class="token punctuation">.</span><span class="token function">RoundTrip</span><span class="token punctuation">(</span>outReq<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		rw<span class="token punctuation">.</span><span class="token function">WriteHeader</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>StatusBadGateway<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	<span class="token comment">// step 3, 把下游请求内容返回给上游</span>
	<span class="token keyword">for</span> key<span class="token punctuation">,</span> value <span class="token operator">:=</span> <span class="token keyword">range</span> res<span class="token punctuation">.</span>Header <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> value <span class="token punctuation">{</span>
			rw<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> v<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	rw<span class="token punctuation">.</span><span class="token function">WriteHeader</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>StatusCode<span class="token punctuation">)</span>
	io<span class="token punctuation">.</span><span class="token function">Copy</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> res<span class="token punctuation">.</span>Body<span class="token punctuation">)</span>
	res<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Serve on :8080"</span><span class="token punctuation">)</span>
	http<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>Pxy<span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
	http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">"0.0.0.0:8080"</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="sock5代理">sock5代理<a class="anchor" href="#sock5代理">¶</a></h3>
<h3 id="反向代理-2">反向代理<a class="anchor" href="#反向代理-2">¶</a></h3>
<p>反向代理：是一种<strong>服务端</strong>的代理技术，帮助服务器做负载均衡、缓存、提供安全校验等，可以隐藏服务器真实IP。</p>
<ol>
<li>代理接受客户端请求，更改请求结构体信息</li>
<li>通过一定的负载均衡算法获取下游服务地址</li>
<li>把请求发送给下游服务器，并获取返回内容</li>
<li>堆返回内容做一些处理，然后返回给客户端</li>
</ol>
<h4 id="http代理-2">http代理<a class="anchor" href="#http代理-2">¶</a></h4>
<p>Go内置了<code>httputil.ReverseProxy</code>类型。内置<code>httputil.NewSingleHostReverseProxy</code>。可以按照其实现自己实现。</p>
<p>简单版：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"bufio"</span>
	<span class="token string">"log"</span>
	<span class="token string">"net/http"</span>
	<span class="token string">"net/url"</span>
<span class="token punctuation">)</span>

<span class="token keyword">var</span> <span class="token punctuation">(</span>
	proxy_addr <span class="token operator">=</span> <span class="token string">"http://127.0.0.1:2003"</span>
	port       <span class="token operator">=</span> <span class="token string">"2002"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">handler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">//step 1 解析代理地址，并更改请求体的协议和主机</span>
	proxy<span class="token punctuation">,</span> err <span class="token operator">:=</span> url<span class="token punctuation">.</span><span class="token function">Parse</span><span class="token punctuation">(</span>proxy_addr<span class="token punctuation">)</span>
	r<span class="token punctuation">.</span>URL<span class="token punctuation">.</span>Scheme <span class="token operator">=</span> proxy<span class="token punctuation">.</span>Scheme
	r<span class="token punctuation">.</span>URL<span class="token punctuation">.</span>Host <span class="token operator">=</span> proxy<span class="token punctuation">.</span>Host

	<span class="token comment">//step 2 请求下游</span>
	transport <span class="token operator">:=</span> http<span class="token punctuation">.</span>DefaultTransport
	resp<span class="token punctuation">,</span> err <span class="token operator">:=</span> transport<span class="token punctuation">.</span><span class="token function">RoundTrip</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		log<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	<span class="token comment">//step 3 把下游请求内容返回给上游</span>
	<span class="token keyword">for</span> k<span class="token punctuation">,</span> vv <span class="token operator">:=</span> <span class="token keyword">range</span> resp<span class="token punctuation">.</span>Header <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> vv <span class="token punctuation">{</span>
			w<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> resp<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	bufio<span class="token punctuation">.</span><span class="token function">NewReader</span><span class="token punctuation">(</span>resp<span class="token punctuation">.</span>Body<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">WriteTo</span><span class="token punctuation">(</span>w<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> handler<span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Start serving on port "</span> <span class="token operator">+</span> port<span class="token punctuation">)</span>
	err <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">":"</span><span class="token operator">+</span>port<span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="ReverseProxy的特殊StatusCode">ReverseProxy的特殊StatusCode<a class="anchor" href="#ReverseProxy的特殊StatusCode">¶</a></h5>
<ul>
<li>100：目前一切正常，客户端可以继续请求
<ul>
<li>客户端Post的数据大于1024字节的时候</li>
<li>客户端需要先发送一个请求，包含一个<code>Expect:100-continue</code>，询问服务端是否愿意接收数据</li>
<li>接收到服务端返回的100-continue应答之后，返回100状态，把数据Post到服务端</li>
<li>相关策略
<ul>
<li>客户端策略
<ul>
<li>如果客户端有 post 数据要上传，可以考虑使用 100-continue 协议。在请求头中加入 {“Expect”:”100-continue”}</li>
<li>如果没有 post 数据，不能使用 100-continue 协议，因为这会让服务端造成误解。</li>
<li>并不是所有的 Server 都会正确实现 100-continue 协议，如果 Client 发送 Expect:100-continue 消息后，在 timeout 时间内无响应，Client 需要立马上传 post 数据。</li>
<li>有些 Server 会错误实现 100-continue 协议，在不需要此协议时返回 100，此时客户端应该忽略。</li>
</ul>
</li>
<li>服务端策略
<ul>
<li>正确情况下，收到请求后，返回 100 或错误码。</li>
<li>如果在发送 100-continue 前收到了 post 数据（客户端提前发送 post 数据），则不发送 100 响应码(略去)。</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>101：服务端发送给客户端升级协议的请求</li>
</ul>
<h5 id="ReverseProxy的特殊Header头">ReverseProxy的特殊Header头<a class="anchor" href="#ReverseProxy的特殊Header头">¶</a></h5>
<ul>
<li>特殊Header头
<ul>
<li>X-Forwarded-For
<ul>
<li>记录最后直连实际服务器之前的整个代理过程</li>
<li>可能被伪造</li>
</ul>
</li>
<li>X-Real-IP
<ul>
<li>请求实际服务器的IP</li>
<li>每过一层代理都会被覆盖掉，只需第一代理设置转发</li>
</ul>
</li>
<li>Connection</li>
<li>TE</li>
<li>Trailer</li>
</ul>
</li>
<li>第一代理除去标准的逐段传输头</li>
</ul>
<h5 id="ReverseProxy">ReverseProxy<a class="anchor" href="#ReverseProxy">¶</a></h5>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> ReverseProxy <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	<span class="token comment">// 控制器必须是一个函数，函数内部可以堆请求进行修改</span>
	Director <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span>

	<span class="token comment">// The transport used to perform proxy requests.</span>
	<span class="token comment">// If nil, http.DefaultTransport is used.</span>
    <span class="token comment">// 连接池</span>
	Transport http<span class="token punctuation">.</span>RoundTripper

	<span class="token comment">// FlushInterval specifies the flush interval</span>
	<span class="token comment">// to flush to the client while copying the</span>
	<span class="token comment">// response body.</span>
	<span class="token comment">// If zero, no periodic flushing is done.</span>
	<span class="token comment">// A negative value means to flush immediately</span>
	<span class="token comment">// after each write to the client.</span>
	<span class="token comment">// The FlushInterval is ignored when ReverseProxy</span>
	<span class="token comment">// recognizes a response as a streaming response, or</span>
	<span class="token comment">// if its ContentLength is -1; for such responses, writes</span>
	<span class="token comment">// are flushed to the client immediately.</span>
    <span class="token comment">// 刷新到客户端的刷新间隔</span>
	FlushInterval time<span class="token punctuation">.</span>Duration

	<span class="token comment">// ErrorLog specifies an optional logger for errors</span>
	<span class="token comment">// that occur when attempting to proxy the request.</span>
	<span class="token comment">// If nil, logging is done via the log package's standard logger.</span>
    <span class="token comment">// 错误记录器</span>
	ErrorLog <span class="token operator">*</span>log<span class="token punctuation">.</span>Logger

	<span class="token comment">// BufferPool optionally specifies a buffer pool to</span>
	<span class="token comment">// get byte slices for use by io.CopyBuffer when</span>
	<span class="token comment">// copying HTTP response bodies.</span>
    <span class="token comment">// 定义缓冲池，在复制http响应时使用，用以提高请求效率</span>
	BufferPool BufferPool

	<span class="token comment">// ModifyResponse is an optional function that modifies the</span>
	<span class="token comment">// Response from the backend. It is called if the backend</span>
	<span class="token comment">// returns a response at all, with any HTTP status code.</span>
	<span class="token comment">// If the backend is unreachable, the optional ErrorHandler is</span>
	<span class="token comment">// called without any call to ModifyResponse.</span>
	<span class="token comment">//</span>
	<span class="token comment">// If ModifyResponse returns an error, ErrorHandler is called</span>
	<span class="token comment">// with its error value. If ErrorHandler is nil, its default</span>
	<span class="token comment">// implementation is used.</span>
    <span class="token comment">// 修改response函数</span>
	ModifyResponse <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">*</span>http<span class="token punctuation">.</span>Response<span class="token punctuation">)</span> <span class="token builtin">error</span>

	<span class="token comment">// ErrorHandler is an optional function that handles errors</span>
	<span class="token comment">// reaching the backend or errors from ModifyResponse.</span>
	<span class="token comment">//</span>
	<span class="token comment">// If nil, the default is to log the provided error and return</span>
	<span class="token comment">// a 502 Status Bad Gateway response.</span>
    <span class="token comment">// 错误处理回调函数，如果为nil时，则遇到错误会显示502</span>
	ErrorHandler <span class="token keyword">func</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>p <span class="token operator">*</span>ReverseProxy<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>rw http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> req <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	transport <span class="token operator">:=</span> p<span class="token punctuation">.</span>Transport
	<span class="token keyword">if</span> transport <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		transport <span class="token operator">=</span> http<span class="token punctuation">.</span>DefaultTransport
	<span class="token punctuation">}</span>
    <span class="token comment">// 验证请求是否终止</span>
	ctx <span class="token operator">:=</span> req<span class="token punctuation">.</span><span class="token function">Context</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> ctx<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token comment">// CloseNotifier predates context.Context, and has been</span>
		<span class="token comment">// entirely superseded by it. If the request contains</span>
		<span class="token comment">// a Context that carries a cancellation signal, don't</span>
		<span class="token comment">// bother spinning up a goroutine to watch the CloseNotify</span>
		<span class="token comment">// channel (if any).</span>
		<span class="token comment">//</span>
		<span class="token comment">// If the request Context has a nil Done channel (which</span>
		<span class="token comment">// means it is either context.Background, or a custom</span>
		<span class="token comment">// Context implementation with no cancellation signal),</span>
		<span class="token comment">// then consult the CloseNotifier if available.</span>
	<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> cn<span class="token punctuation">,</span> ok <span class="token operator">:=</span> rw<span class="token punctuation">.</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>CloseNotifier<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		<span class="token keyword">var</span> cancel context<span class="token punctuation">.</span>CancelFunc
		ctx<span class="token punctuation">,</span> cancel <span class="token operator">=</span> context<span class="token punctuation">.</span><span class="token function">WithCancel</span><span class="token punctuation">(</span>ctx<span class="token punctuation">)</span>
		<span class="token keyword">defer</span> <span class="token function">cancel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		notifyChan <span class="token operator">:=</span> cn<span class="token punctuation">.</span><span class="token function">CloseNotify</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">select</span> <span class="token punctuation">{</span>
			<span class="token keyword">case</span> <span class="token operator">&lt;-</span>notifyChan<span class="token punctuation">:</span>
				<span class="token function">cancel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token keyword">case</span> <span class="token operator">&lt;-</span>ctx<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
			<span class="token punctuation">}</span>
		<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
    <span class="token comment">// 设置请求ctx信息</span>
	outreq <span class="token operator">:=</span> req<span class="token punctuation">.</span><span class="token function">Clone</span><span class="token punctuation">(</span>ctx<span class="token punctuation">)</span>
	<span class="token keyword">if</span> req<span class="token punctuation">.</span>ContentLength <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		outreq<span class="token punctuation">.</span>Body <span class="token operator">=</span> <span class="token boolean">nil</span> <span class="token comment">// Issue 16036: nil Body for http.Transport retries</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> outreq<span class="token punctuation">.</span>Body <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token comment">// Reading from the request body after returning from a handler is not</span>
		<span class="token comment">// allowed, and the RoundTrip goroutine that reads the Body can outlive</span>
		<span class="token comment">// this handler. This can lead to a crash if the handler panics (see</span>
		<span class="token comment">// Issue 46866). Although calling Close doesn't guarantee there isn't</span>
		<span class="token comment">// any Read in flight after the handle returns, in practice it's safe to</span>
		<span class="token comment">// read after closing it.</span>
		<span class="token keyword">defer</span> outreq<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
    <span class="token comment">// 深拷贝header</span>
	<span class="token keyword">if</span> outreq<span class="token punctuation">.</span>Header <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		outreq<span class="token punctuation">.</span>Header <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>Header<span class="token punctuation">)</span> <span class="token comment">// Issue 33142: historical behavior was to always allocate</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 修改req</span>
	p<span class="token punctuation">.</span><span class="token function">Director</span><span class="token punctuation">(</span>outreq<span class="token punctuation">)</span>
	outreq<span class="token punctuation">.</span>Close <span class="token operator">=</span> <span class="token boolean">false</span>
	<span class="token comment">// Upgrade头的特殊处理</span>
	reqUpType <span class="token operator">:=</span> <span class="token function">upgradeType</span><span class="token punctuation">(</span>outreq<span class="token punctuation">.</span>Header<span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ascii<span class="token punctuation">.</span><span class="token function">IsPrint</span><span class="token punctuation">(</span>reqUpType<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		p<span class="token punctuation">.</span><span class="token function">getErrorHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> req<span class="token punctuation">,</span> fmt<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"client tried to switch to invalid protocol %q"</span><span class="token punctuation">,</span> reqUpType<span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token function">removeConnectionHeaders</span><span class="token punctuation">(</span>outreq<span class="token punctuation">.</span>Header<span class="token punctuation">)</span>

	<span class="token comment">// Remove hop-by-hop headers to the backend. Especially</span>
	<span class="token comment">// important is "Connection" because we want a persistent</span>
	<span class="token comment">// connection, regardless of what the client sent to us.</span>
    <span class="token comment">// 删除后端的逐段标题</span>
	<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> h <span class="token operator">:=</span> <span class="token keyword">range</span> hopHeaders <span class="token punctuation">{</span>
		outreq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Del</span><span class="token punctuation">(</span>h<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>

	<span class="token comment">// Issue 21096: tell backend applications that care about trailer support</span>
	<span class="token comment">// that we support trailers. (We do, but we don't go out of our way to</span>
	<span class="token comment">// advertise that unless the incoming client request thought it was worth</span>
	<span class="token comment">// mentioning.) Note that we look at req.Header, not outreq.Header, since</span>
	<span class="token comment">// the latter has passed through removeConnectionHeaders.</span>
	<span class="token keyword">if</span> httpguts<span class="token punctuation">.</span><span class="token function">HeaderValuesContainsToken</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>Header<span class="token punctuation">[</span><span class="token string">"Te"</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string">"trailers"</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		outreq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"Te"</span><span class="token punctuation">,</span> <span class="token string">"trailers"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>

	<span class="token comment">// After stripping all the hop-by-hop connection headers above, add back any</span>
	<span class="token comment">// necessary for protocol upgrades, such as for websockets.</span>
	<span class="token keyword">if</span> reqUpType <span class="token operator">!=</span> <span class="token string">""</span> <span class="token punctuation">{</span>
		outreq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"Connection"</span><span class="token punctuation">,</span> <span class="token string">"Upgrade"</span><span class="token punctuation">)</span>
		outreq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"Upgrade"</span><span class="token punctuation">,</span> reqUpType<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 追加clint IP信息</span>
	<span class="token keyword">if</span> clientIP<span class="token punctuation">,</span> <span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">:=</span> net<span class="token punctuation">.</span><span class="token function">SplitHostPort</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token comment">// If we aren't the first proxy retain prior</span>
		<span class="token comment">// X-Forwarded-For information as a comma+space</span>
		<span class="token comment">// separated list and fold multiple headers into one.</span>
		prior<span class="token punctuation">,</span> ok <span class="token operator">:=</span> outreq<span class="token punctuation">.</span>Header<span class="token punctuation">[</span><span class="token string">"X-Forwarded-For"</span><span class="token punctuation">]</span>
		omit <span class="token operator">:=</span> ok <span class="token operator">&amp;&amp;</span> prior <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token comment">// Issue 38079: nil now means don't populate the header</span>
		<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>prior<span class="token punctuation">)</span> <span class="token operator">&gt;</span> <span class="token number">0</span> <span class="token punctuation">{</span>
			clientIP <span class="token operator">=</span> strings<span class="token punctuation">.</span><span class="token function">Join</span><span class="token punctuation">(</span>prior<span class="token punctuation">,</span> <span class="token string">", "</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">", "</span> <span class="token operator">+</span> clientIP
		<span class="token punctuation">}</span>
		<span class="token keyword">if</span> <span class="token operator">!</span>omit <span class="token punctuation">{</span>
			outreq<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Set</span><span class="token punctuation">(</span><span class="token string">"X-Forwarded-For"</span><span class="token punctuation">,</span> clientIP<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 向下游请求数据</span>
	res<span class="token punctuation">,</span> err <span class="token operator">:=</span> transport<span class="token punctuation">.</span><span class="token function">RoundTrip</span><span class="token punctuation">(</span>outreq<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		p<span class="token punctuation">.</span><span class="token function">getErrorHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> outreq<span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	<span class="token comment">// Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)</span>
    <span class="token comment">// 处理升级协议请求</span>
	<span class="token keyword">if</span> res<span class="token punctuation">.</span>StatusCode <span class="token operator">==</span> http<span class="token punctuation">.</span>StatusSwitchingProtocols <span class="token punctuation">{</span>
		<span class="token keyword">if</span> <span class="token operator">!</span>p<span class="token punctuation">.</span><span class="token function">modifyResponse</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> res<span class="token punctuation">,</span> outreq<span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">}</span>
		p<span class="token punctuation">.</span><span class="token function">handleUpgradeResponse</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> outreq<span class="token punctuation">,</span> res<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 移除逐段头部</span>
	<span class="token function">removeConnectionHeaders</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>Header<span class="token punctuation">)</span>

	<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> h <span class="token operator">:=</span> <span class="token keyword">range</span> hopHeaders <span class="token punctuation">{</span>
		res<span class="token punctuation">.</span>Header<span class="token punctuation">.</span><span class="token function">Del</span><span class="token punctuation">(</span>h<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 修改返回数据</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>p<span class="token punctuation">.</span><span class="token function">modifyResponse</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> res<span class="token punctuation">,</span> outreq<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 拷贝头部信息</span>
	<span class="token function">copyHeader</span><span class="token punctuation">(</span>rw<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> res<span class="token punctuation">.</span>Header<span class="token punctuation">)</span>

	<span class="token comment">// The "Trailer" header isn't included in the Transport's response,</span>
	<span class="token comment">// at least for *http.Transport. Build it up from Trailer.</span>
	announcedTrailers <span class="token operator">:=</span> <span class="token function">len</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>Trailer<span class="token punctuation">)</span>
	<span class="token keyword">if</span> announcedTrailers <span class="token operator">&gt;</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		trailerKeys <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token function">len</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>Trailer<span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">for</span> k <span class="token operator">:=</span> <span class="token keyword">range</span> res<span class="token punctuation">.</span>Trailer <span class="token punctuation">{</span>
			trailerKeys <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>trailerKeys<span class="token punctuation">,</span> k<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
		rw<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token string">"Trailer"</span><span class="token punctuation">,</span> strings<span class="token punctuation">.</span><span class="token function">Join</span><span class="token punctuation">(</span>trailerKeys<span class="token punctuation">,</span> <span class="token string">", "</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 写入状态码</span>
	rw<span class="token punctuation">.</span><span class="token function">WriteHeader</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>StatusCode<span class="token punctuation">)</span>
	<span class="token comment">// 周期刷新内容到response</span>
	err <span class="token operator">=</span> p<span class="token punctuation">.</span><span class="token function">copyResponse</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> res<span class="token punctuation">.</span>Body<span class="token punctuation">,</span> p<span class="token punctuation">.</span><span class="token function">flushInterval</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">defer</span> res<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token comment">// Since we're streaming the response, if we run into an error all we can do</span>
		<span class="token comment">// is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler</span>
		<span class="token comment">// on read error while copying body.</span>
		<span class="token keyword">if</span> <span class="token operator">!</span><span class="token function">shouldPanicOnCopyError</span><span class="token punctuation">(</span>req<span class="token punctuation">)</span> <span class="token punctuation">{</span>
			p<span class="token punctuation">.</span><span class="token function">logf</span><span class="token punctuation">(</span><span class="token string">"suppressing panic for copyResponse error in test; copy error: %v"</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">}</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>ErrAbortHandler<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	res<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// close now, instead of defer, to populate res.Trailer</span>

	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>Trailer<span class="token punctuation">)</span> <span class="token operator">&gt;</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token comment">// Force chunking if we saw a response trailer.</span>
		<span class="token comment">// This prevents net/http from calculating the length for short</span>
		<span class="token comment">// bodies and adding a Content-Length.</span>
		<span class="token keyword">if</span> fl<span class="token punctuation">,</span> ok <span class="token operator">:=</span> rw<span class="token punctuation">.</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>Flusher<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
			fl<span class="token punctuation">.</span><span class="token function">Flush</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>

	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>Trailer<span class="token punctuation">)</span> <span class="token operator">==</span> announcedTrailers <span class="token punctuation">{</span>
		<span class="token function">copyHeader</span><span class="token punctuation">(</span>rw<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> res<span class="token punctuation">.</span>Trailer<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	<span class="token keyword">for</span> k<span class="token punctuation">,</span> vv <span class="token operator">:=</span> <span class="token keyword">range</span> res<span class="token punctuation">.</span>Trailer <span class="token punctuation">{</span>
		k <span class="token operator">=</span> http<span class="token punctuation">.</span>TrailerPrefix <span class="token operator">+</span> k
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> v <span class="token operator">:=</span> <span class="token keyword">range</span> vv <span class="token punctuation">{</span>
			rw<span class="token punctuation">.</span><span class="token function">Header</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="Connection">Connection<a class="anchor" href="#Connection">¶</a></h5>
<ul>
<li>标记请求发起方与第一代理的状态</li>
<li>决定当前事务完成后，是否会关闭网络
<ul>
<li>Connection：keep-alive 不关闭网络</li>
<li>Connection：close 关闭网络</li>
<li>Connection：upgrade 协议升级</li>
</ul>
</li>
</ul>
<h5 id="TE">TE<a class="anchor" href="#TE">¶</a></h5>
<p>TE是requesy_header，表示希望使用的传输编码类型。</p>
<p>如：<code>TE:trailers,deflate;q=0.5</code>表示，期望在采用分块传输编码响应中接收挂载字段，zlib编码，0.5优先级排序。</p>
<h5 id="Trailer">Trailer<a class="anchor" href="#Trailer">¶</a></h5>
<p>Trailer是response header，允许发送方在消息后面添加额外的元信息。</p>
<p>如：<code>Trailer:Expires</code>表示Expires将出现在分块信息的结尾。</p>
<h5 id="去除逐段传输头">去除逐段传输头<a class="anchor" href="#去除逐段传输头">¶</a></h5>
<p>代理过程中上述只发生在客户端和第一代理中。因此第一代理需要除去标准的逐段传输头（hop-by-hop）</p>
<ul>
<li>逐段传输头都需要在Connection头中列出</li>
<li>第一代理必须处理它们且不转发</li>
<li>逐段传输头：<code>Keep-Alive,Transfer-Encoding,TE,Connection,Trailer,Upgrade,Proxy-Authorization,Proxy-Authenticate</code></li>
</ul>
<h4 id="socks5代理">socks5代理<a class="anchor" href="#socks5代理">¶</a></h4>
<h2 id="负载均衡">负载均衡<a class="anchor" href="#负载均衡">¶</a></h2>
<h3 id="随机负载均衡">随机负载均衡<a class="anchor" href="#随机负载均衡">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"errors"</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"math/rand"</span>
	<span class="token string">"strings"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> RandomBalance <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	curIndex <span class="token builtin">int</span>
	rss      <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
	<span class="token comment">//观察主体</span>
	conf LoadBalanceConf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RandomBalance<span class="token punctuation">)</span> <span class="token function">Add</span><span class="token punctuation">(</span>params <span class="token operator">...</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"param len 1 at least"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	addr <span class="token operator">:=</span> params<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
	r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">,</span> addr<span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RandomBalance<span class="token punctuation">)</span> <span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> <span class="token string">""</span>
	<span class="token punctuation">}</span>
	r<span class="token punctuation">.</span>curIndex <span class="token operator">=</span> rand<span class="token punctuation">.</span><span class="token function">Intn</span><span class="token punctuation">(</span><span class="token function">len</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> r<span class="token punctuation">.</span>rss<span class="token punctuation">[</span>r<span class="token punctuation">.</span>curIndex<span class="token punctuation">]</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RandomBalance<span class="token punctuation">)</span> <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> r<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RandomBalance<span class="token punctuation">)</span> <span class="token function">SetConf</span><span class="token punctuation">(</span>conf LoadBalanceConf<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	r<span class="token punctuation">.</span>conf <span class="token operator">=</span> conf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RandomBalance<span class="token punctuation">)</span> <span class="token function">Update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceZkConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceCheckConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token boolean">nil</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="轮询负载均衡">轮询负载均衡<a class="anchor" href="#轮询负载均衡">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"errors"</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"strings"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> RoundRobinBalance <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	curIndex <span class="token builtin">int</span>
	rss      <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
	<span class="token comment">//观察主体</span>
	conf LoadBalanceConf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Add</span><span class="token punctuation">(</span>params <span class="token operator">...</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"param len 1 at least"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	addr <span class="token operator">:=</span> params<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
	r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">,</span> addr<span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> <span class="token string">""</span>
	<span class="token punctuation">}</span>
	lens <span class="token operator">:=</span> <span class="token function">len</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">)</span> <span class="token comment">//5</span>
	<span class="token keyword">if</span> r<span class="token punctuation">.</span>curIndex <span class="token operator">&gt;=</span> lens <span class="token punctuation">{</span>
		r<span class="token punctuation">.</span>curIndex <span class="token operator">=</span> <span class="token number">0</span>
	<span class="token punctuation">}</span>
	curAddr <span class="token operator">:=</span> r<span class="token punctuation">.</span>rss<span class="token punctuation">[</span>r<span class="token punctuation">.</span>curIndex<span class="token punctuation">]</span>
	r<span class="token punctuation">.</span>curIndex <span class="token operator">=</span> <span class="token punctuation">(</span>r<span class="token punctuation">.</span>curIndex <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">%</span> lens
	<span class="token keyword">return</span> curAddr
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> r<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RoundRobinBalance<span class="token punctuation">)</span> <span class="token function">SetConf</span><span class="token punctuation">(</span>conf LoadBalanceConf<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	r<span class="token punctuation">.</span>conf <span class="token operator">=</span> conf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>RoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceZkConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceCheckConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token boolean">nil</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="加权轮询负载均衡">加权轮询负载均衡<a class="anchor" href="#加权轮询负载均衡">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"errors"</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"strconv"</span>
	<span class="token string">"strings"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> WeightRoundRobinBalance <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	curIndex <span class="token builtin">int</span>
	rss      <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>WeightNode
	rsw      <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span>
	<span class="token comment">//观察主体</span>
	conf LoadBalanceConf
<span class="token punctuation">}</span>

<span class="token keyword">type</span> WeightNode <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	addr            <span class="token builtin">string</span>
	weight          <span class="token builtin">int</span> <span class="token comment">//权重值</span>
	currentWeight   <span class="token builtin">int</span> <span class="token comment">//节点当前权重</span>
	effectiveWeight <span class="token builtin">int</span> <span class="token comment">//有效权重</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>WeightRoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Add</span><span class="token punctuation">(</span>params <span class="token operator">...</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token number">2</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"param len need 2"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	parInt<span class="token punctuation">,</span> err <span class="token operator">:=</span> strconv<span class="token punctuation">.</span><span class="token function">ParseInt</span><span class="token punctuation">(</span>params<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">64</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">}</span>
	node <span class="token operator">:=</span> <span class="token operator">&amp;</span>WeightNode<span class="token punctuation">{</span>addr<span class="token punctuation">:</span> params<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> weight<span class="token punctuation">:</span> <span class="token function">int</span><span class="token punctuation">(</span>parInt<span class="token punctuation">)</span><span class="token punctuation">}</span>
	node<span class="token punctuation">.</span>effectiveWeight <span class="token operator">=</span> node<span class="token punctuation">.</span>weight
	r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">,</span> node<span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>WeightRoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span>
	total <span class="token operator">:=</span> <span class="token number">0</span>
	<span class="token keyword">var</span> best <span class="token operator">*</span>WeightNode
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token function">len</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>rss<span class="token punctuation">)</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		w <span class="token operator">:=</span> r<span class="token punctuation">.</span>rss<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
		<span class="token comment">//step 1 统计所有有效权重之和</span>
		total <span class="token operator">+=</span> w<span class="token punctuation">.</span>effectiveWeight
		<span class="token comment">//step 2 变更节点临时权重为的节点临时权重+节点有效权重</span>
		w<span class="token punctuation">.</span>currentWeight <span class="token operator">+=</span> w<span class="token punctuation">.</span>effectiveWeight
		<span class="token comment">//step 3 有效权重默认与权重相同，通讯异常时-1, 通讯成功+1，直到恢复到weight大小</span>
		<span class="token keyword">if</span> w<span class="token punctuation">.</span>effectiveWeight <span class="token operator">&lt;</span> w<span class="token punctuation">.</span>weight <span class="token punctuation">{</span>
			w<span class="token punctuation">.</span>effectiveWeight<span class="token operator">++</span>
		<span class="token punctuation">}</span>
		<span class="token comment">//step 4 选择最大临时权重点节点</span>
		<span class="token keyword">if</span> best <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token operator">||</span> w<span class="token punctuation">.</span>currentWeight <span class="token operator">&gt;</span> best<span class="token punctuation">.</span>currentWeight <span class="token punctuation">{</span>
			best <span class="token operator">=</span> w
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> best <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> <span class="token string">""</span>
	<span class="token punctuation">}</span>
	<span class="token comment">//step 5 变更临时权重为 临时权重-有效权重之和</span>
	best<span class="token punctuation">.</span>currentWeight <span class="token operator">-=</span> total
	<span class="token keyword">return</span> best<span class="token punctuation">.</span>addr
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>WeightRoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> r<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>WeightRoundRobinBalance<span class="token punctuation">)</span> <span class="token function">SetConf</span><span class="token punctuation">(</span>conf LoadBalanceConf<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	r<span class="token punctuation">.</span>conf <span class="token operator">=</span> conf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>WeightRoundRobinBalance<span class="token punctuation">)</span> <span class="token function">Update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceZkConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"WeightRoundRobinBalance get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token boolean">nil</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> r<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceCheckConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"WeightRoundRobinBalance get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		r<span class="token punctuation">.</span>rss <span class="token operator">=</span> <span class="token boolean">nil</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			r<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="一致性负载均衡">一致性负载均衡<a class="anchor" href="#一致性负载均衡">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"errors"</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"hash/crc32"</span>
	<span class="token string">"sort"</span>
	<span class="token string">"strconv"</span>
	<span class="token string">"strings"</span>
	<span class="token string">"sync"</span>
<span class="token punctuation">)</span>

<span class="token keyword">type</span> Hash <span class="token keyword">func</span><span class="token punctuation">(</span>data <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">)</span> <span class="token builtin">uint32</span>

<span class="token keyword">type</span> UInt32Slice <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">uint32</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>s UInt32Slice<span class="token punctuation">)</span> <span class="token function">Len</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> <span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>s UInt32Slice<span class="token punctuation">)</span> <span class="token function">Less</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> j <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> s<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">&lt;</span> s<span class="token punctuation">[</span>j<span class="token punctuation">]</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>s UInt32Slice<span class="token punctuation">)</span> <span class="token function">Swap</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> j <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	s<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> s<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> s<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">,</span> s<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> ConsistentHashBanlance <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	mux      sync<span class="token punctuation">.</span>RWMutex
	hash     Hash
	replicas <span class="token builtin">int</span>               <span class="token comment">//复制因子</span>
	keys     UInt32Slice       <span class="token comment">//已排序的节点hash切片</span>
	hashMap  <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">uint32</span><span class="token punctuation">]</span><span class="token builtin">string</span> <span class="token comment">//节点哈希和Key的map,键是hash值，值是节点key</span>

	<span class="token comment">//观察主体</span>
	conf LoadBalanceConf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">NewConsistentHashBanlance</span><span class="token punctuation">(</span>replicas <span class="token builtin">int</span><span class="token punctuation">,</span> fn Hash<span class="token punctuation">)</span> <span class="token operator">*</span>ConsistentHashBanlance <span class="token punctuation">{</span>
	m <span class="token operator">:=</span> <span class="token operator">&amp;</span>ConsistentHashBanlance<span class="token punctuation">{</span>
		replicas<span class="token punctuation">:</span> replicas<span class="token punctuation">,</span>
		hash<span class="token punctuation">:</span>     fn<span class="token punctuation">,</span>
		hashMap<span class="token punctuation">:</span>  <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">uint32</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> m<span class="token punctuation">.</span>hash <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token comment">//最多32位,保证是一个2^32-1环</span>
		m<span class="token punctuation">.</span>hash <span class="token operator">=</span> crc32<span class="token punctuation">.</span>ChecksumIEEE
	<span class="token punctuation">}</span>
	<span class="token keyword">return</span> m
<span class="token punctuation">}</span>

<span class="token comment">// 验证是否为空</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>ConsistentHashBanlance<span class="token punctuation">)</span> <span class="token function">IsEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> <span class="token function">len</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span>
<span class="token punctuation">}</span>

<span class="token comment">// Add 方法用来添加缓存节点，参数为节点key，比如使用IP</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>ConsistentHashBanlance<span class="token punctuation">)</span> <span class="token function">Add</span><span class="token punctuation">(</span>params <span class="token operator">...</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token function">len</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"param len 1 at least"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	addr <span class="token operator">:=</span> params<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
	c<span class="token punctuation">.</span>mux<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> c<span class="token punctuation">.</span>mux<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token comment">// 结合复制因子计算所有虚拟节点的hash值，并存入m.keys中，同时在m.hashMap中保存哈希值和key的映射</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> c<span class="token punctuation">.</span>replicas<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		hash <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">hash</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span>strconv<span class="token punctuation">.</span><span class="token function">Itoa</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span> <span class="token operator">+</span> addr<span class="token punctuation">)</span><span class="token punctuation">)</span>
		c<span class="token punctuation">.</span>keys <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">,</span> hash<span class="token punctuation">)</span>
		c<span class="token punctuation">.</span>hashMap<span class="token punctuation">[</span>hash<span class="token punctuation">]</span> <span class="token operator">=</span> addr
	<span class="token punctuation">}</span>
	<span class="token comment">// 对所有虚拟节点的哈希值进行排序，方便之后进行二分查找</span>
	sort<span class="token punctuation">.</span><span class="token function">Sort</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token comment">// Get 方法根据给定的对象获取最靠近它的那个节点</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>ConsistentHashBanlance<span class="token punctuation">)</span> <span class="token function">Get</span><span class="token punctuation">(</span>key <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span><span class="token function">IsEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> <span class="token string">""</span><span class="token punctuation">,</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"node is empty"</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	hash <span class="token operator">:=</span> c<span class="token punctuation">.</span><span class="token function">hash</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">)</span>

	<span class="token comment">// 通过二分查找获取最优节点，第一个"服务器hash"值大于"数据hash"值的就是最优"服务器节点"</span>
	idx <span class="token operator">:=</span> sort<span class="token punctuation">.</span><span class="token function">Search</span><span class="token punctuation">(</span><span class="token function">len</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> c<span class="token punctuation">.</span>keys<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">&gt;=</span> hash <span class="token punctuation">}</span><span class="token punctuation">)</span>

	<span class="token comment">// 如果查找结果 大于 服务器节点哈希数组的最大索引，表示此时该对象哈希值位于最后一个节点之后，那么放入第一个节点中</span>
	<span class="token keyword">if</span> idx <span class="token operator">==</span> <span class="token function">len</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		idx <span class="token operator">=</span> <span class="token number">0</span>
	<span class="token punctuation">}</span>
	c<span class="token punctuation">.</span>mux<span class="token punctuation">.</span><span class="token function">RLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> c<span class="token punctuation">.</span>mux<span class="token punctuation">.</span><span class="token function">RUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> c<span class="token punctuation">.</span>hashMap<span class="token punctuation">[</span>c<span class="token punctuation">.</span>keys<span class="token punctuation">[</span>idx<span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>ConsistentHashBanlance<span class="token punctuation">)</span> <span class="token function">SetConf</span><span class="token punctuation">(</span>conf LoadBalanceConf<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	c<span class="token punctuation">.</span>conf <span class="token operator">=</span> conf
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>ConsistentHashBanlance<span class="token punctuation">)</span> <span class="token function">Update</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceZkConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		c<span class="token punctuation">.</span>keys <span class="token operator">=</span> <span class="token boolean">nil</span>
		c<span class="token punctuation">.</span>hashMap <span class="token operator">=</span> <span class="token boolean">nil</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			c<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> conf<span class="token punctuation">,</span> ok <span class="token operator">:=</span> c<span class="token punctuation">.</span>conf<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>LoadBalanceCheckConf<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Update get conf:"</span><span class="token punctuation">,</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		c<span class="token punctuation">.</span>keys <span class="token operator">=</span> <span class="token boolean">nil</span>
		c<span class="token punctuation">.</span>hashMap <span class="token operator">=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">uint32</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
		<span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> ip <span class="token operator">:=</span> <span class="token keyword">range</span> conf<span class="token punctuation">.</span><span class="token function">GetConf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			c<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>strings<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token operator">...</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">不二</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://buerlog.top/2020/12/18/cheng-xu-she-ji/go/go-yu-yan-wang-guan-kai-fa/">http://buerlog.top/2020/12/18/cheng-xu-she-ji/go/go-yu-yan-wang-guan-kai-fa/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">不二</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go/">
                                    <span class="chip bg-color">Go</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/12/27/jing-yan-zong-jie/hexo-bo-ke-da-jian-ji-lu/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/经验总结/hexo.jpg" class="responsive-img" alt="Hexo博客搭建记录">
                        
                        <span class="card-title">Hexo博客搭建记录</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-12-27
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%BB%8F%E9%AA%8C%E6%80%BB%E7%BB%93/" class="post-category">
                                    经验总结
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Hexo/">
                        <span class="chip bg-color">Hexo</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/11/21/jing-yan-zong-jie/windows10-chang-yong-ruan-jian-ji-lu/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/经验总结/win10.jpeg" class="responsive-img" alt="Windows10常用软件记录">
                        
                        <span class="card-title">Windows10常用软件记录</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-11-21
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%BB%8F%E9%AA%8C%E6%80%BB%E7%BB%93/" class="post-category">
                                    经验总结
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Windows/">
                        <span class="chip bg-color">Windows</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 不二博客<br />'
            + '文章作者: 不二<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="1901371647"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2018-2023</span>
            
            <span id="year">2018</span>
            <a href="/about" target="_blank">不二</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">263.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2018";
                    var startMonth = "5";
                    var startDate = "25";
                    var startHour = "17";
                    var startMinute = "20";
                    var startSecond = "53";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/weiyouwozuiku" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:weiyouwozuiku@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1104891151" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1104891151" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/he-he-9-35-47" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/he-he-9-35-47" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <script src='https://unpkg.com/mermaid@8.14.0/dist/mermaid.min.js'></script>
    <script>
      if (window.mermaid) {
        mermaid.initialize({theme: 'forest'});
      }
    </script>
  

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?943a68f473d421f2d98228f74edc63d0";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="150"
        src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
